import uuid, datetime
from django.shortcuts import HttpResponse, redirect, render
from app01.forms.account import SendSmsForm, LoginSMSForm, LoginForm, RegisterModelForm
from django.http import JsonResponse
# from web import models
from app01 import models
from utils.image_code import check_code
from io import BytesIO
from django.db.models import Q
from rbac.service.init_permission import init_permission


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {"form": form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过，写入数据库
        # 用户表中新建一条数据
        instance = form.save()  # instance = models.UserInfo.objects.create(**form.cleaned_data)
        return JsonResponse({'status': True, 'data': '/login/'})

    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """ 发送短信 """
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户名输入正确，登录成功
        phone = form.cleaned_data['phone']
        # 将用户信息写入到Session中
        user_object = models.UserInfo.objects.filter(phone=phone).first()
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)  # 修改Session的过期时间
        # 用户权限信息的初始化
        init_permission(user_object, request)
        return JsonResponse({'status': True, 'data': '/index/'})

    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """用户名和密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        password = form.cleaned_data['password']
        print('222222222222', name, password)
        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        user_object = models.UserInfo.objects.filter(Q(email=name) | Q(phone=name)).filter(
            password=password).first()

        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)  # 修改Session的过期时间
            # 用户权限信息的初始化
            init_permission(user_object, request)
            return redirect('index')
        form.add_error('name', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    image_object, code = check_code()

    request.session['image_code'] = code
    request.session.set_expiry(60)  # 修改Session的过期时间

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('login')


def index(request):
    """
    首页
    :param request:
    :return:
    """
    return render(request, 'index.html')
